import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { inject } from 'vue'
import { useRouter } from 'vue-router'

export const userInfoStore = defineStore('user', () => {
  const api = inject('$api')
  const router = useRouter()

  const user = ref(null)
  const isLoggedIn = ref(false)
  const token = ref(localStorage.getItem('token') || null)

  const displayName = computed(() => {
    return user.value?.realName || user.value?.username || '用户'
  })

  // 初始化用户状态（从localStorage恢复）
  const initializeUser = () => {
    const savedToken = localStorage.getItem('token')
    const savedUser = localStorage.getItem('user')

    if (savedToken && savedUser) {
      try {
        token.value = savedToken
        user.value = JSON.parse(savedUser)
        isLoggedIn.value = true
        console.log('用户状态已从本地存储恢复')
      } catch (error) {
        console.error('解析用户信息失败:', error)
        // 如果解析失败，清除无效数据
        clearUserData()
      }
    }
  }

  // 清除用户数据
  const clearUserData = () => {
    user.value = null
    isLoggedIn.value = false
    token.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 验证token有效性
  const validateToken = async () => {
    if (!token.value) {
      console.log('未找到token，验证失败')
      return false
    }

    try {
      const response = await api.auth.validateToken()

      if (response.code === 200 && response.data.valid) {
        // 更新用户信息（可能用户信息有变化）
        if (response.data.user) {
          user.value = response.data.user
          localStorage.setItem('user', JSON.stringify(response.data.user))
          console.log('Token验证成功，用户信息已更新')
        }
        return true
      } else {
        console.warn('Token验证失败:', response.message)
        clearUserData()
        return false
      }
    } catch (error) {
      console.error('Token验证请求失败:', error)

      // 如果是网络错误，不立即清除数据，可能是暂时性问题
      if (error.code === 'NETWORK_ERROR' || !error.response) {
        console.warn('网络错误，保留本地登录状态')
        return true // 或者根据需求返回 false
      }

      // 如果是认证错误，清除数据
      if (error.response?.status === 401 || error.response?.status === 403) {
        clearUserData()
      }
      return false
    }
  }

  //登录
  const login = async (credentials) => {
    try {
      const response = await api.auth.login(credentials)
      user.value = response.data.user
      isLoggedIn.value = true
      token.value = response.data.token

      localStorage.setItem('token', response.data.token)
      localStorage.setItem('user', JSON.stringify(response.data.user))

      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  //注册
  const register = async (userData) => {
    try {
      const response = await api.auth.register(userData)
      return response
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  //退出登录
  const logout = async () => {
    try {
      await api.auth.logout()
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      user.value = null
      isLoggedIn.value = false
      token.value = null

      localStorage.removeItem('token')
      localStorage.removeItem('user')

      router.push('/')
    }
  }

  initializeUser()

  return {
    user,
    isLoggedIn,
    token,
    displayName,
    login,
    register,
    logout,
    initializeUser,
    validateToken,
    clearUserData,
  }
})
